package com.dranie.servlet;

import org.apache.commons.io.FileUtils;

import javax.imageio.ImageIO;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: xi
 * Date: 13-7-31
 * Time: 下午2:19
 * To change this template use File | Settings | File Templates.
 */
public class JcropCutServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("do cut");
        try {
            saveImg(request, response);
        } catch (Exception e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        request.getRequestDispatcher("/plugin/jcrop.jsp").forward(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    // 保存修剪后的头像
    private Map<String, Object> saveImg(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, Object> mv = new HashMap<String, Object>();
        String xStr = request.getParameter("x");
        String yStr = request.getParameter("y");
        String wStr = request.getParameter("w");
        String hStr = request.getParameter("h");
        int x = 0;
        int y = 0;
        int w = 300;
        int h = 300;
        if (null != xStr && !"".equals(xStr)) {
            x = Integer.parseInt(xStr);
        }
        if (null != yStr && !"".equals(yStr)) {
            y = Integer.parseInt(yStr);
        }
        if (null != wStr && !"".equals(wStr)) {
            w = Integer.parseInt(wStr);
        }
        if (null != hStr && !"".equals(hStr)) {
            h = Integer.parseInt(hStr);
        }
        String imgName = request.getParameter("imgName");
        ServletContext context = getServletContext();
        String path = context.getRealPath("/upload/temp");
        //String path = request.getRealPath("/");
        String sourcePath = path + "/";
//        imgName = MD5.crypt(imgName);
        String fileName = sourcePath + imgName;
        File imgFile = new File(fileName);
        BufferedImage bi = ImageIO.read(imgFile);
        BufferedImage out = null;
        if (w > 0 && h > 0 && bi.getWidth() >= w && bi.getHeight() >= h) {
            out = bi.getSubimage(x, y, w, h);
        } else {
            out = bi.getSubimage(0, 0, bi.getWidth(), bi.getHeight());
        }
        out = resizeImage(out, BufferedImage.TYPE_INT_RGB, w, h);
        ByteArrayOutputStream o = new ByteArrayOutputStream();
        String suffix = imgName.substring(imgName.lastIndexOf(".") + 1);
        ImageIO.write(out, suffix, o);
        byte[] byteObj = o.toByteArray();
        String saveName = "g" + new Date().getTime() + "." + suffix;
        String savePath = context.getRealPath("/upload/goods") + "/" + saveName;
        String dbPath = "/upload/goods/" + saveName;
        FileUtils.writeByteArrayToFile(new File(savePath), byteObj);

        if (imgFile.exists()) {
            imgFile.delete();
        }
        request.setAttribute("imgName", saveName);
        request.setAttribute("imgId", 200);
        request.setAttribute("photoUrl", dbPath);
        return mv;
    }

    //对图片大小进行缩放处理
    private BufferedImage resizeImage(BufferedImage originalImage, int type, int width, int height) {
        MathUtil mathUtil = new MathUtil();
        Double rate = 0.0;
        if (width < 130 && height < 130) {
            BufferedImage resizedImage = new BufferedImage(width, height, type);
            Graphics2D g = resizedImage.createGraphics();
            g.drawImage(originalImage, 0, 0, width, height, null);
            g.dispose();
            return resizedImage;
        } else {
            rate = mathUtil.divide(new Double(height), new Double(130));
            height = (int) mathUtil.divide(new Double(height), rate);
            width = (int) mathUtil.divide(new Double(width), rate);
        }
        BufferedImage resizedImage = new BufferedImage(width, height, type);
        Graphics2D g = resizedImage.createGraphics();
        g.drawImage(originalImage, 0, 0, width, height, null);
        g.dispose();
        return resizedImage;
    }
}

class MathUtil {
    public double divide(Double d, Double rate) {
        return rate == 0.0 ? d : d / rate;
    }
}